package com.campus.util;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SendMsg {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    private  String openid;

    @Value("${wx.templateId}")
    private String templateId;

    private final Map<String,String> convertion;

    //对需要替换的Key进行初始化在Map中
    public SendMsg(){
        convertion= new HashMap<>();
        //xxx为原始key，yyy为微信指定的key
        convertion.put("xxx","yyy");
    }
    /**
     *
     * @param ids 接受者的OpenId集合，如果只有一个用户，就是size为1的List
     * @param notices 原始数据，需要将Key转换为小程序指定的字符串，经过conversion方法进行转换
     * @param path 需要转发的页面
     */
    public  void sendMsg(List<String> ids,Map<String,String> notices,String path){
        notices=this.conversion(notices);
        for(String id:ids){
            this.openid=id;
            //1:获取token（接口调用凭证）
            String token = queryToken();
            //2:发送订阅消息
            send(token,notices,path);
        }
    }

    // 1: 获取 access_token  (2h过期)
    public String queryToken(){

        String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        tokenUrl = tokenUrl + "&appid=" + appId + "&secret=" + secret;
        String result = HttpUtil.get(tokenUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String token = jsonObject.get("access_token").toString();
        return token;
    }
    //教育通知今日事宜
    public  void send(String token, Map<String,String> notices, String pageName){
        String msgUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
        msgUrl = msgUrl + "?access_token=" + token;
        // 设置模板参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("touser", openid);
        paramMap.put("template_id", templateId);
        paramMap.put("page",pageName);
        // 设置data 模板内容
        HashMap<String, Object> data = new HashMap<>();
        for(String key: notices.keySet()){
            data.put(key,formatParam(notices.get(key)));
        }
        paramMap.put("data", data);
        // 转json字符串
        String jsonObject = JSONUtil.toJsonStr(paramMap);
        String result= HttpUtil.post(msgUrl, jsonObject);
    }

    public HashMap<String, Object> formatParam(String value){
        HashMap<String, Object> data = new HashMap<>();
        data.put("value", value);
        return data;
    }

    private Map<String,String> conversion(Map<String,String> map){
        Map<String,String> converted = new HashMap<>();
        for(String key:map.keySet()){
            String s = convertion.get(key);
            if(s!=null){
                converted.put(s,map.get(key));
            }else{
                converted.put(key,map.get(key));
            }
        }
        return converted;
    }
}

